<template>
    <el-space direction="vertical" fill class="pro-table">
        <div class="pro-table__header">
            <el-space>
                <el-button type="default">刷新</el-button>
                <el-button type="primary">新增</el-button>
                <el-button type="danger">删除</el-button>
            </el-space>
            <el-space>
                <el-input placeholder="请输入" />
                <el-button color="#626aef">搜索</el-button>
            </el-space>
        </div>
        <div class="pro-table__body">
      <el-table v-loading="loading" stripe border :data="list">
        <slot name="default"></slot>
      </el-table>
    </div>

    <div class="pro-table__footer">
      <el-pagination
        v-model:currentPage="params.current"
        v-model:pageSize="params.pageSize"
        :total="total"
        :page-sizes="[2, 4, 6, 8, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        background
      />
    </div>
    </el-space>
</template>

<script>
export default {
  name: "ProTable",

  props: {
    /**
     *    params: {
     *      current: 1,
     *      pageSize: 10
     *    }
     *
     * async (params) => {
     *    // 获取数据
     *    // 返回一个包含有 success、list、total 的对象
     *    return {
     *      success: true, // 数据是否OK，需要 boolean 的值
     *      list: [], // 表格的数据
     *      total: 1, // 数据总条数
     *    }
     * }
     */
    request: {
      type: Function,
      required: true,
    },

    /**
     * 默认当前页
     */
    defaultCurrent: {
      type: Number,
      default: 1,
    },

    /**
     * 默认每页显示条数
     */
    defaultPageSize: {
      type: Number,
      default: 10,
    },
  },

  data() {
    return {
      params: {
        current: this.defaultCurrent, // 当前页
        pageSize: this.defaultPageSize, // 每页显示条数
      },
      list: [], // 表格数据
      total: 1, // 表格数据总条数
      loading: false, // 表格数据是否请求中
    };
  },

  watch: {
    params: {
      handler() {
        this.refresh();
      },
      deep: true,
    },
  },

  methods: {
    async refresh() {
      // 请求中
      this.loading = true;

      const { success, list, total } = await this.request(this.params);

      if (success) {
        // 将 list 与 total 赋值
        this.list = list;
        this.total = total;

        // 请求完成
        this.loading = false;
      } else {
        // 如果不成功，请求完成
        this.loading = false;
      }
    },
  },

  created() {
    // 调用 refresh
    this.refresh();
  },
};
</script>

<style lang="scss" scoped>
.pro-table {
  display: flex;

  &__header {
    display: flex;
    justify-content: space-between;
  }

  &__footer {
    display: flex;
    justify-content: flex-end;
  }
}
</style>